package com.jdaw.algorithm.prim;

import javax.xml.crypto.Data;

public class PrimAlgorithm {
    public static void main(String[] args) {
        char[] data=new char[]{'A','B','C','D','E','F','G'};
        int verxs= data.length;
        //10000表示两个点不连通
        int [][]weight=new int[][]{
                {10000,5,7,10000,10000,10000,2},
                {5,10000,10000,9,10000,10000,3},
                {7,10000,10000,10000,8,10000,10000},
                {10000,9,10000,10000,10000,4,10000},
                {10000,10000,8,10000,10000,5,4},
                {10000,10000,10000,4,5,10000,6},
                {2,3,10000,10000,4,6,10000},};
        MGraph mGraph=new MGraph(verxs);
        MinTree minTree=new MinTree();
        minTree.createGraph(mGraph,verxs,data,weight);
        minTree.showGraph(mGraph);
        minTree.prim(mGraph,0);
    }
}

//创建最小生成树，就是村庄的图
class MinTree{
    public void createGraph(MGraph mGraph,int verxs,char[] data,int[][] weight){
        int i,j;
        for(i=0;i<verxs;i++){
            mGraph.data[i]=data[i];
            for(j=0;j<verxs;j++){
                mGraph.weight[i][j]=weight[i][j];
            }
        }

    }
    //显示图
    public void showGraph(MGraph mGraph){
        for(int i=0;i<mGraph.weight.length;i++){
            for (int j=0;j<mGraph.weight[0].length;j++){
                if(mGraph.weight[i][j]>9999){
                    System.out.print("0 ");
                }else {
                    System.out.print(mGraph.weight[i][j] + " ");
                }
            }
            System.out.println("");
        }
    }

    //生成最小生成树的算法
    public void prim(MGraph mGraph,int v){
        //v表示从图的第几个节点开始生成
        //visited记录节点是否被访问过,0为未访问，1为已访问
        int[] visited=new int[mGraph.verxs];
        visited[v]=1;
        //h1h2记录两个顶点的下标
        int h1=-1,h2=-1;
        int minWeight=10000;
        for(int k=1;k<mGraph.verxs;k++){ //一共有verxs-1条边，需要verxs-1次循环
            for(int i=0;i<mGraph.verxs;i++){//遍历已访问过的节点
                for (int j=0;j<mGraph.verxs;j++){
                    if(visited[i]==1&&visited[j]==0&&mGraph.weight[i][j]<minWeight){
                        minWeight=mGraph.weight[i][j];
                        h1=i;
                        h2=j;
                    }
                }
            }
            System.out.println(mGraph.data[h1]+"<->"+mGraph.data[h2]);
            visited[h2]=1;
            minWeight=10000;
        }
    }
}

class MGraph{
    int verxs;
    char[] data;
    int[][] weight;

    public MGraph(int verxs) {
        this.verxs = verxs;
        data=new char[verxs];
        weight=new int[verxs][verxs];
    }
}